#include <my_header.h>
/* Usage: ./client */
int main(void){                                  
    
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    char *ip = "192.168.229.128";
    char *port= "8080";

    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(port));
    sockaddr.sin_addr.s_addr = inet_addr(ip);

    int res_conn = connect(socket_fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
    ERROR_CHECK(res_conn, -1, "connect");

    // 信息在应用层有边界
    int file_name_len;
    recv(socket_fd, &file_name_len, sizeof(int), MSG_WAITALL);

    char file_name[60] = { 0 };
    recv(socket_fd,file_name, file_name_len, MSG_WAITALL);
    printf("%s\n", file_name);

    int file_fd = open(file_name, O_RDWR | O_CREAT, 0600);
    ERROR_CHECK(file_fd, -1, "open");

    // 接收文件大小
    off_t file_size = 0;
    recv(socket_fd, &file_size, sizeof(off_t), MSG_WAITALL);
    printf("file_size :%ld\n", file_size );

    // 接收文件之前，应该让文件足够大
    int  rs=   ftruncate(file_fd, file_size);
    ERROR_CHECK(rs, -1, "ftruncate");

    void *p  = mmap(NULL, file_size, PROT_READ | PROT_WRITE, MAP_SHARED, file_fd, 0);
    ERROR_CHECK(p, NULL, "mmap");

    recv(socket_fd, p, file_size, MSG_WAITALL);

    // 销毁文件映射
    munmap(p, file_size);

    // 关闭socket和文件描述符
    close(socket_fd);
    close(file_fd);
    return 0;
}


